/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.livelab.java;

import com.livelab.model.Login;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;


/**
 * Backing bean that supports "studentForm" in "index.xhtml"
 * 
 * @author Dakota
 */
@ManagedBean
@SessionScoped
public class StudentLoginBean extends Login{
    
    private String courseId;        //student course id
    private boolean newLogin = false;
    
    /**
     * Constructor
     */
    public StudentLoginBean() {
        super();
    }
    
    @Override
    public void login(){
        
        try {
            //check for student with supplied username and password
            ResultSet rs = db.executeQuery("SELECT * FROM agsstudent WHERE username = '" + getUsername() + "' AND password = '" + getPassword() + "';");
            FacesContext context = FacesContext.getCurrentInstance();
            
            //found
            if(rs != null && rs.next()){
                setLoggedIn(true);
                courseId = rs.getString("courseId");
                context.addMessage(null, new FacesMessage("Logged In", "Student " + rs.getString("username")));
                newLogin = true;      
            }
            //not found
            else{     
                context.addMessage(null, new FacesMessage("Username/Password", "Invalid combination"));
                setUsername("");
                setPassword("");
            }
        } catch (SQLException ex) {
            Logger.getLogger(StudentLoginBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    /**
     * Logs out Student
     */
    public void logout(){
        setLoggedIn(false);
        setUsername("");
        setPassword("");
    }
    
    /*
     * GETTERS
     */
    
    public String getCourseId(){
        return courseId;
    }
    
    public boolean isNewLogin(){
        return newLogin;
    }
    
    /*
     * SETTERS
     */
    
    public void setNewLogin(boolean b){
        newLogin = b;
    }
}
